<template>
  <div class="type-page">
    <PageContainer back noTab title="分类列表">
      <div class="container-wrapper">
        <SearchModule @search="onSearch"></SearchModule>
        <div class="type-list">
          <TypeList :options="typeList" @change="onTypeChange"></TypeList>
        </div>
        <div id="type-main-container" class="main-container">
          <ProduceList
            v-if="containerHeight"
            :height="containerHeight"
            listApi="/api/erp/erpCategoryTreeRelate/listAll"
            :extParams="{
              categoryId: categoryId,
              name: searchText,
            }"
          >
          </ProduceList>
        </div>
      </div>
    </PageContainer>
  </div>
</template>

<script setup>
import {ref, getCurrentInstance, onMounted} from 'vue';
import PageContainer from '@/components/PageContainer/index.vue';
import ProduceList from '@/components/ProductList/index.vue';
import TypeList from '@/components/TypeList/index.vue';
import SearchModule from '@/components/SearchModule/index.vue';
import {useRouter} from '@/hooks/useRouter.ts';
import {getTreeTypeList} from '@/api/type';

const {getPageQuery, push} = useRouter();

const typeList = ref([]);

const containerHeight = ref(0);
const instance = getCurrentInstance();
const initHeight = () => {
  const query = uni.createSelectorQuery().in(instance?.proxy);
  setTimeout(() => {
    query
      .select(`#type-main-container`)
      .boundingClientRect((result) => {
        if (result?.height) {
          containerHeight.value = result.height;
        } else {
          console.log('error', '-> ', instance);
        }
      })
      .exec();
  }, 100);
};

const onTypeChange = (data) => {
  push({
    path: '/pages/productList/index',
    query: {
      id: data.id,
    },
  });
};

const initTypeList = async (id) => {
  const data = await getTreeTypeList(id);
  typeList.value = data.records.map((item) => {
    return {
      ...item,
      label: item.name,
      value: item.id,
      icon: item.url,
    };
  });
  initHeight();
};

// 搜索
const searchText = ref('');
const onSearch = (data) => {
  searchText.value = data;
};

const categoryId = ref('');
onMounted(async () => {
  const queryData = getPageQuery();
  await initTypeList(queryData.id);
  categoryId.value = queryData.id;
});
</script>

<style lang="less" scoped>
.type-page {
  .container-wrapper {
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .title {
      margin-top: 10px;
      margin-bottom: -10px;
      padding: 0 24px;
      color: #777;
      font-size: 12px;
    }
    .type-list {
      width: 100%;
      .list {
        width: 100%;
      }
    }
    .main-container {
      box-sizing: border-box;
      flex: 1;
    }
  }
}
</style>
